package com.wpx.fileSys.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import com.wpx.fileSys.dao.FileDao;
import com.wpx.fileSys.dao.UserDao;
import com.wpx.fileSys.dao.impl.FileDaoImpl;
import com.wpx.fileSys.dao.impl.UserDaoImpl;

import sun.security.util.Password;

/**
 * Servlet implementation class userLoginServlet
 */
@WebServlet("/userLoginServlet")
public class userLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public userLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");	

		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = null;	
		out = response.getWriter();
		
		String username=request.getParameter("username");
		String pwd=request.getParameter("pwd");
		

		HttpSession session=request.getSession();
		
		
		UserDao userDao=new UserDaoImpl();
		JSONObject result=userDao.loginSys(username, pwd);
		if (result.getString("msg").contentEquals("0")) {
			session.setAttribute("username", username);
			session.setAttribute("token", result.getString("token"));
			result.remove("token");
			FileDao dao=new FileDaoImpl();
			String msg=result.getString("msg");
//			if (dao.deleteFiles(username)) {
//				if (!dao.updateFiles(username)) {
//					msg="更新过程中出现错误";
//				}
//			}else {
//				msg="删除过程中出现错误";
//			}
			result.put("msg", msg);
		}
		
		
		out.write(result.toString());
		
//		RequestDispatcher dispatcher = request.getRequestDispatcher("/index.html");
//		dispatcher .forward(request, response);
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
